package com.wumao.service;

import com.wumao.NotFoundException;
import com.wumao.mapper.TagMapper;
import com.wumao.pojo.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gaowumao
 * @Decripted
 * @Email none-j@qq.com
 * @create 2021-04-16 15:53
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Transactional
    @Override
    public Tag addTag(Tag tag) {
        return tagMapper.save(tag);
    }

    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagMapper.findById(id).get();
    }

    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagMapper.findAll(pageable);
    }

    @Transactional
    @Override
    public void deleteTag(Long id) {
        tagMapper.deleteById(id);
    }

    @Override
    public List<Tag> listTags() {
        return tagMapper.findAll();
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = null;
        sort= Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = null;
        pageable =  PageRequest.of(0,size,sort);
        return tagMapper.findTop(pageable);
    }

    @Override
    public List<Tag> listTags(String ids) {
        return tagMapper.findAllById(convertToList(ids));
    }

    private List<Long> convertToList(String ids){
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids!= null){
            String[] idarray = ids.split(",");
            for (int i=0;i<idarray.length;i++){
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Transactional
    @Override
    public Tag getTagByName(String name) {
        return tagMapper.queryByName(name);
    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagMapper.findById(id).get();
        if (t == null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(tag,t);
        return tagMapper.save(t);
    }
}
